/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.menosehmais.framework.converter;

import br.com.caelum.vraptor.Convert;
import br.com.caelum.vraptor.Converter;
import br.com.caelum.vraptor.converter.ConversionError;
import br.com.caelum.vraptor.ioc.ApplicationScoped;
import java.util.ResourceBundle;
import org.joda.time.LocalTime;

/**
 * ISO8601 format (HH:mm:ss.SSS).
 * @author Quintino
 */
//@Convert(LocalTime.class)
//@ApplicationScoped
public class LocalTimeConverter implements Converter<LocalTime> {

    @Override
    public LocalTime convert(String value, Class<? extends LocalTime> type, ResourceBundle bundle) {
        return fromString(value);
    }

    public static LocalTime fromString(String value) {
        LocalTime time = null;
        int hourOfDay = 0, minuteOfHour = 0, secondOfMinute = 0, millisOfSecond = 0;

        try {
            if (value == null || value.trim().isEmpty()) {
                return null;
            } else {
                value = value.trim();
                String fields[] = value.split(":|\\.");

                if(value.matches("^\\d{1,2}:\\d{1,2}:\\d{1,2}\\.\\d{1,3}$")) {
                    hourOfDay = Integer.parseInt(fields[0]);
                    minuteOfHour = Integer.parseInt(fields[1]);
                    secondOfMinute = Integer.parseInt(fields[2]);
                    millisOfSecond = Integer.parseInt(fields[3]);
                    time = new LocalTime(hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);
                } else if(value.matches("^\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
                    hourOfDay = Integer.parseInt(fields[0]);
                    minuteOfHour = Integer.parseInt(fields[1]);
                    secondOfMinute = Integer.parseInt(fields[2]);
                    time = new LocalTime(hourOfDay, minuteOfHour, secondOfMinute);
                } else if(value.matches("^\\d{1,2}:\\d{1,2}$")) {
                    hourOfDay = Integer.parseInt(fields[0]);
                    minuteOfHour = Integer.parseInt(fields[1]);
                    time = new LocalTime(hourOfDay, minuteOfHour);
                } else {
                    throw new ConversionError( "LocalTime: " + value + ", é inválido. " );
                }
            }

        } catch (Exception e) {
            throw new ConversionError( "LocalTime: " + value + ", é inválido. " + e.getMessage() );
        }

        return time;
    }

    public static String asString(LocalTime time){
        if(time == null) {
            return null;
        }
        return time.toString("HH:mm:ss.SSS");
    }
}
